module rd_id (
    input                   clk         ,
    input                   rst_n       ,
    input         [2:0]     key_down    ,
    input         [7:0]     rd_data     ,
    input                   trans_done  ,
    output   reg            rw_flag     ,
    output   reg  [23:0]    addr_data   ,
    output   reg            data_vld    ,
    output   reg  [7:0]     wr_data     
);

reg    [23:0]   data_r;

reg		[1:0]	cnt_byte	;
wire			add_cnt_byte;
wire			end_cnt_byte;
reg             end_cnt_byte_r0;

always @(posedge clk or negedge rst_n)begin 
    if(!rst_n)begin
        rw_flag <= 1'd0;
    end 
    else if(key_down[0])begin 
        rw_flag <= 1'b1;
    end 
    else if(end_cnt_byte)begin 
        rw_flag <= 1'b0;
    end 
end

always @(posedge clk or negedge rst_n)begin 
   if(!rst_n)begin
        cnt_byte <= 'd0;
    end 
    else if(add_cnt_byte)begin 
        if(end_cnt_byte)begin 
            cnt_byte <= 'd0;
        end
        else begin 
            cnt_byte <= cnt_byte + 1'b1;
        end 
    end
end 

assign add_cnt_byte = trans_done && rw_flag;
assign end_cnt_byte = add_cnt_byte && cnt_byte == 4-1;

//---------<wr_data>------------------------------------------------- 

always @(*)begin 
    case(cnt_byte)
        0   :   begin  wr_data = 8'h9f; end
        default : wr_data = 8'h00;
    endcase 
end

//---------<data_r>------------------------------------------------- 

always @(posedge clk or negedge rst_n)begin 
    if(!rst_n)begin
        data_r <= 'd0;
    end 
    else if(trans_done && cnt_byte >=1'b1)begin 
        data_r <= {data_r[15:0],rd_data};
    end 
end

//---------<end_cnt_byte_r0>------------------------------------------------- 

always @(posedge clk or negedge rst_n)begin 
    if(!rst_n)begin
        end_cnt_byte_r0 <= 1'd0;
    end 
    else begin 
        end_cnt_byte_r0 <= end_cnt_byte;
    end 
end

//---------<addr_data data_vld>------------------------------------------------- 

always @(posedge clk or negedge rst_n)begin 
    if(!rst_n)begin
        addr_data <= 'd0;
        data_vld <=1'b0;
    end 
    else if(end_cnt_byte_r0)begin 
        addr_data <= data_r;
        data_vld <= 1'b1;
    end 
    else begin 
        addr_data <= addr_data;
        data_vld <= 1'b0;
    end 
end

endmodule